/**
 * 
 */
package jvs.vfs.util.note;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import x.java.io.File;
import x.java.io.FileWriter;


/**
 * @author qiangli
 * 
 */
public class NoteHelper {
	static final SimpleDateFormat cdf = new SimpleDateFormat(
			"yyyy-MM-dd.HH.mm.ss.SSS");

	public static final String COMMENT_MP = "/my/note";

	/**
	 *  date, name, author, body separated by \r\n, terminated by a blank line \r\n\r\n
	 * @param path v:/
	 * @param name
	 * @param author
	 * @param body
	 * @throws IOException
	 */
	synchronized public static void addNote(String path, String name,
			String author, String body) throws IOException {
		if (isEmpty(body)) {
			return;
		}
		File cf = getNoteFile(path);
		FileWriter fw = new FileWriter(cf, true);
		Date now = new Date();
		String date = cdf.format(now);
		fw.write(date + "\r\n");
		if (isEmpty(author)) {
			author = "~";
		}
		fw.write(author + "\r\n");
		if (isEmpty(name)) {
			name = author;
		}
		fw.write(name + "\r\n");
		String[] sa = body.split("\r\n");
		int len = sa.length;
		for (int i = 0; i < len; i++) {
			String s = sa[i];
			if (s.length() > 0) {
				fw.write(s);
				fw.write("\r\n");
			}
		}
		//
		fw.write("\r\n");
		fw.close();
	}
	
	public static File getNoteFile(String path) throws IOException {
		path = normalize(path);
		File cf = new File(COMMENT_MP + path + ".cmt");
		File pf = (x.java.io.File)cf.getParentFile();
		if (!pf.exists()) {
			pf.mkdirs();
		}
		return cf;
	}

	static boolean isEmpty(String line) {
		return (line == null || line.length() == 0);
	}

	private static String normalize(String path) throws IOException {
		//remove v: if any
		if (path.startsWith("v:") || path.startsWith("V:")) {
			path = path.substring(2);
		}
		//absolute path required
		if (path.charAt(0) != '/') {
			throw new IOException("Invalid path. "+path);
		}
		//can't add note to note folder
		if (path.startsWith(COMMENT_MP)) {
			throw new IOException("Note not supported for internal note folder"); 
		}
		int len = path.length();
		//remove trailing / if not root
		if (len > 1 && path.charAt(len -1) == '/') {
			path = path.substring(0, len - 1);
		}
		return path;
	}
	
	public static NoteIterator notes(String path, String crlf) throws IOException {
		return new NoteIterator(path, crlf);
	}

	
	static String parseDate(String s) {
		Date d;
		try {
			d = cdf.parse(s);
			return d.toString();
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return s;
	}

	private NoteHelper() {
	}
}
